<?php

namespace Xin\Hyperf\Fortify\Process;

use Hyperf\Process\AbstractProcess;
use Psr\Container\ContainerInterface;
use Swoole\Coroutine\Server as CoServer;
use Swoole\Server;

class CustomProcess extends AbstractProcess
{
    private static $processInc = 0;

    /**
     * @var callable
     */
    protected $handler = null;

    /**
     * @var bool
     */
    protected $isEnable = true;

    /**
     * @param ContainerInterface $container
     * @param callable $handler
     * @param array $options
     */
    public function __construct(ContainerInterface $container, callable $handler, array $options = [])
    {
        parent::__construct($container);

        self::$processInc++;
        $this->name = isset($options['name']) ? $options['name'] . "Process" : "CustomProcess[" . self::$processInc . "]";
        $this->nums = empty($options['nums']) ? 1 : $options['nums'];
        $this->handler = $handler;
    }

    /**
     * @param CoServer|Server $server
     * @return bool
     */
    public function isEnable($server): bool
    {
        return $this->isEnable;
    }

    public function handle(): void
    {
//        \Closure::fromCallable($this->handler)->call($this);
        call_user_func($this->handler, $this);
    }

    public function getSwooleProcess()
    {
        return $this->process;
    }

    public function getRestartInterval()
    {
        return $this->restartInterval;
    }

    public function setRestartInterval($restartInterval)
    {
        $this->restartInterval = $restartInterval;
    }

    public function getRecvLength()
    {
        return $this->recvLength;
    }

    public function setRecvLength(int $recvLength)
    {
        $this->recvLength = $recvLength;
    }

    public function getRecvTimeout(): float
    {
        return $this->recvTimeout;
    }

    public function setRecvTimeout(float $recvTimeout)
    {
        $this->recvTimeout = $recvTimeout;
    }

    public function kill()
    {
        return $this->process->close();
    }

    public function input($data)
    {
        $this->process->push($data);
    }

    public function read($size = 1024 * 1024)
    {
        $this->process->read($size);
    }
}
